﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 对象池
/// </summary>
public class GameObjectPool {
	private List<GameObject> poolList = new List<GameObject>();
	private GameObject _prefab = null;
    private int allNum = 0;
	public GameObjectPool(GameObject prefab){
		_prefab = prefab;
	}
	/// <summary>
    /// 获取对象
	/// </summary>
	/// <param name="position"></param>
	/// <returns></returns>
	public GameObject GetObject(Vector3 position = default(Vector3),Quaternion quaternion = default(Quaternion))
	{
        GameObject _object = null;
        if (poolList.Count > 0)
        {
            _object = poolList[0];
            poolList.RemoveAt(0);
            _object.SetActive(true);
        }
        else
        {
            _object = GameObject.Instantiate(_prefab, position, quaternion);
            allNum++;
        }
        _object.transform.localPosition = position;
        return _object;
	}
    /// <summary>
    /// 可用个数
    /// </summary>
    public int Useable()
    {
        return poolList.Count;
    }
    /// <summary>
    /// 总个数
    /// </summary>
    public int Count()
    {
        return allNum;
    }
	/// <summary>
    /// 放回对象池
	/// </summary>
	/// <param name="_object"></param>
	public void PutObject(GameObject _object)
	{
        _object.SendMessage("Unuse",SendMessageOptions.DontRequireReceiver);
        _object.SetActive(false);
        poolList.Add(_object);
	}
	/// <summary>
    /// 清空对象池
	/// </summary>
    public void ReleasePool(){
        foreach (var item in poolList)
        {
            GameObject.Destroy(item);
        }
        poolList.Clear();
	}
}
